<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CertMate - SSL Certificate Manager</title>
    <link rel="icon" type="image/x-icon" href="/favicon.ico">
    <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        /* Prevent flash of white background in dark mode */
        @media (prefers-color-scheme: dark) {
            html {
                background-color: #111827 !important;
            }
        }
    </style>
    <script>
        tailwind.config = {
            darkMode: 'media', // Automatically respects system preference
            theme: {
                extend: {
                    colors: {
                        primary: '#3b82f6',
                        secondary: '#1e40af',
                    }
                }
            }
        }
    </script>
</head>
<body class="bg-gray-50 dark:bg-gray-900 min-h-screen transition-colors duration-200">
    <!-- Navigation -->
    <nav class="bg-white dark:bg-gray-800 shadow-sm border-b dark:border-gray-700">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16">
                <div class="flex items-center">
                    <div class="flex-shrink-0">
                        <i class="fas fa-shield-alt text-primary text-2xl"></i>
                    </div>
                    <div class="ml-3">
                        <h1 class="text-xl font-semibold text-gray-900 dark:text-white">CertMate</h1>
                        <p class="text-sm text-gray-500 dark:text-gray-400">SSL Certificate Manager</p>
                    </div>
                </div>
                <div class="flex items-center space-x-4">
                    <a href="/" class="px-3 py-2 rounded-md text-sm font-medium text-primary bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-700">
                        <i class="fas fa-certificate mr-1"></i> Certificates
                    </a>
                    <a href="/settings" class="px-3 py-2 rounded-md text-sm font-medium text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-gray-700">
                        <i class="fas fa-cog mr-1"></i> Settings
                    </a>
                    <a href="/help" class="px-3 py-2 rounded-md text-sm font-medium text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-gray-700">
                        <i class="fas fa-question-circle mr-1"></i> Help
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <!-- Main Content -->
    <div class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
        <!-- Create Certificate Form -->
        <div class="bg-white dark:bg-gray-800 shadow-lg rounded-xl mb-6 border border-gray-200 dark:border-gray-700 overflow-hidden">
            <div class="px-6 py-5 border-b border-gray-200 dark:border-gray-700 bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-gray-800 dark:to-gray-700">
                <div class="flex items-center justify-between">
                    <div>
                        <h3 class="text-xl font-bold text-gray-900 dark:text-white flex items-center">
                            <i class="fas fa-plus-circle mr-2 text-primary"></i>
                            Create New Certificate
                        </h3>
                        <p class="text-sm text-gray-600 dark:text-gray-300 mt-1">Generate SSL certificates with multiple CA providers and advanced DNS challenge support</p>
                    </div>
                    <div class="hidden lg:flex items-center space-x-2">
                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300">
                            <i class="fas fa-leaf mr-1"></i>
                            Let's Encrypt
                        </span>
                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300">
                            <i class="fas fa-shield-alt mr-1"></i>
                            DigiCert
                        </span>
                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300">
                            <i class="fas fa-building mr-1"></i>
                            Private CA
                        </span>
                    </div>
                </div>
            </div>
            <div class="px-6 py-6">
                <form id="createCertForm" class="space-y-6">
                    <!-- Main Certificate Configuration -->
                    <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">
                        <div class="space-y-4">
                            <div>
                                <label for="domain" class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                    <i class="fas fa-globe mr-2 text-blue-500"></i>
                                    Domain Name
                                </label>
                                <input type="text" id="domain" name="domain" 
                                       class="block w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-lg shadow-sm py-3 px-4 focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary transition-all duration-200 placeholder-gray-400"
                                       placeholder="example.com or *.example.com" required>
                                <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                    <i class="fas fa-info-circle mr-1"></i>
                                    Supports wildcard domains (*.example.com) and single domains
                                </p>
                            </div>
                            
                            <div>
                                <label for="ca_provider_select" class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                    <i class="fas fa-certificate mr-2 text-green-500"></i>
                                    Certificate Authority
                                </label>
                                <select id="ca_provider_select" name="ca_provider" 
                                        class="block w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-lg shadow-sm py-3 px-4 focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary transition-all duration-200"
                                        onchange="updateCAProviderInfo()">
                                    <option value="">🔧 Use default from settings</option>
                                    <option value="letsencrypt">🌿 Let's Encrypt (Free, DV certificates)</option>
                                    <option value="digicert">🛡️ DigiCert ACME (Enterprise, DV/OV/EV)</option>
                                    <option value="private_ca">🏢 Private CA (Internal/Corporate)</option>
                                </select>
                                <div id="ca-provider-info" class="mt-2 text-xs text-gray-600 dark:text-gray-400 hidden">
                                    <!-- CA provider info will be populated here -->
                                </div>
                            </div>
                        </div>
                        
                        <div class="space-y-4">
                            <div>
                                <label for="dns_provider_select" class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                    <i class="fas fa-server mr-2 text-purple-500"></i>
                                    DNS Provider
                                </label>
                                <select id="dns_provider_select" name="dns_provider" 
                                        class="block w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-lg shadow-sm py-3 px-4 focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary transition-all duration-200"
                                        onchange="updateAccountSelection()">
                                    <option value="">🔧 Use default from settings</option>
                                    <option value="cloudflare">☁️ Cloudflare</option>
                                    <option value="route53">🚀 AWS Route53</option>
                                    <option value="digitalocean">🌊 DigitalOcean</option>
                                    <option value="azure">☁️ Azure DNS</option>
                                    <option value="google">📊 Google Cloud DNS</option>
                                    <option value="powerdns">⚡ PowerDNS</option>
                                    <option value="rfc2136">🔧 RFC2136 (Generic)</option>
                                    <option value="linode">🌐 Linode</option>
                                    <option value="vultr">⚡ Vultr</option>
                                    <option value="hetzner">🇩🇪 Hetzner</option>
                                    <option value="gandi">🇫🇷 Gandi</option>
                                    <option value="ovh">🇫🇷 OVH</option>
                                    <option value="namecheap">💰 Namecheap</option>
                                    <option value="porkbun">🐷 Porkbun</option>
                                    <option value="godaddy">🌐 GoDaddy</option>
                                    <option value="dnsmadeeasy">📡 DNS Made Easy</option>
                                    <option value="nsone">1️⃣ NS1</option>
                                    <option value="he-ddns">🌪️ Hurricane Electric</option>
                                    <option value="dynudns">🔄 Dynu</option>
                                </select>
                                <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                    <i class="fas fa-info-circle mr-1"></i>
                                    DNS provider for domain validation challenge
                                </p>
                            </div>
                            
                            <div id="account-selection-container" style="display: none;">
                                <label for="account_select" class="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
                                    <i class="fas fa-user mr-2 text-orange-500"></i>
                                    Account
                                </label>
                                <select id="account_select" name="account_id" 
                                        class="block w-full border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-lg shadow-sm py-3 px-4 focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary transition-all duration-200">
                                    <option value="">🔧 Use default account</option>
                                </select>
                                <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                    <i class="fas fa-info-circle mr-1"></i>
                                    For multi-account DNS provider setups
                                </p>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Advanced Options (Collapsible) -->
                    <div class="border-t border-gray-200 dark:border-gray-600 pt-6">
                        <button type="button" onclick="toggleAdvancedOptions()" 
                                class="flex items-center text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-primary transition-colors duration-200">
                            <i class="fas fa-cog mr-2"></i>
                            Advanced Options
                            <i id="advanced-chevron" class="fas fa-chevron-down ml-2 transform transition-transform duration-200"></i>
                        </button>
                        
                        <div id="advanced-options" class="hidden mt-4 p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label class="flex items-center text-sm text-gray-700 dark:text-gray-300">
                                        <input type="checkbox" id="wildcard-cert" class="rounded border-gray-300 text-primary focus:ring-primary dark:bg-gray-700 dark:border-gray-600">
                                        <span class="ml-2">
                                            <i class="fas fa-asterisk mr-1 text-yellow-500"></i>
                                            Generate wildcard certificate
                                        </span>
                                    </label>
                                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400 ml-6">
                                        Covers *.domain.com and domain.com
                                    </p>
                                </div>
                                
                                <div>
                                    <label class="flex items-center text-sm text-gray-700 dark:text-gray-300">
                                        <input type="checkbox" id="staging-cert" class="rounded border-gray-300 text-primary focus:ring-primary dark:bg-gray-700 dark:border-gray-600">
                                        <span class="ml-2">
                                            <i class="fas fa-flask mr-1 text-orange-500"></i>
                                            Use staging environment
                                        </span>
                                    </label>
                                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400 ml-6">
                                        For testing (Let's Encrypt only)
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Action Button -->
                    <div class="flex flex-col sm:flex-row items-center justify-between space-y-3 sm:space-y-0">
                        <div class="text-sm text-gray-600 dark:text-gray-400">
                            <i class="fas fa-shield-alt mr-1 text-green-500"></i>
                            Free SSL certificates with automatic renewal
                        </div>
                        <button type="submit" 
                                class="w-full sm:w-auto inline-flex items-center justify-center px-8 py-3 border border-transparent text-base font-medium rounded-lg shadow-lg text-white bg-gradient-to-r from-primary to-secondary hover:from-secondary hover:to-primary focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary transform transition-all duration-200 hover:scale-105">
                            <i class="fas fa-magic mr-2"></i>
                            Create Certificate
                        </button>
                    </div>
                    
                    <!-- Quick Info -->
                    <div class="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-700 rounded-lg p-4">
                        <div class="flex items-start">
                            <i class="fas fa-lightbulb text-blue-500 mt-0.5 mr-3"></i>
                            <div class="text-sm text-blue-800 dark:text-blue-300">
                                <p class="font-medium">💡 Quick Tips:</p>
                                <ul class="mt-1 space-y-1 text-xs">
                                    <li>• Wildcard certificates work for unlimited subdomains</li>
                                    <li>• DigiCert requires EAB credentials (configured in Settings)</li>
                                    <li>• Private CAs are perfect for internal/corporate use</li>
                                    <li>• Certificates auto-renew 30 days before expiry</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- Statistics Cards -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6" id="statsCards">
            <!-- Stats will be populated here -->
        </div>

        <!-- Certificates List -->
        <div class="bg-white dark:bg-gray-800 shadow-sm rounded-lg border border-gray-200 dark:border-gray-700">
            <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-700/50 rounded-t-lg">
                <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between space-y-3 lg:space-y-0">
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Your Certificates</h3>
                    <div class="flex flex-col sm:flex-row items-stretch sm:items-center space-y-2 sm:space-y-0 sm:space-x-2 lg:space-x-3">
                        <div class="relative">
                            <input type="text" id="certificateSearch" placeholder="Search certificates..." 
                                   class="pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-lg focus:ring-2 focus:ring-primary focus:border-primary text-sm bg-white shadow-sm transition-shadow duration-200 w-full sm:w-48">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <i class="fas fa-search text-gray-400"></i>
                            </div>
                        </div>
                        <select id="statusFilter" class="border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary focus:border-primary bg-white shadow-sm transition-shadow duration-200">
                            <option value="all">All Status</option>
                            <option value="valid">Valid</option>
                            <option value="expiring">Expiring Soon</option>
                            <option value="expired">Expired</option>
                        </select>
                        <button onclick="checkAllDeploymentStatuses()" 
                                class="inline-flex items-center px-3 py-2 border border-indigo-300 dark:border-indigo-600 shadow-sm text-sm font-medium rounded-lg text-indigo-700 dark:text-indigo-300 bg-indigo-50 dark:bg-indigo-900/30 hover:bg-indigo-100 dark:hover:bg-indigo-900/50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors duration-200 whitespace-nowrap">
                            <i class="fas fa-sync mr-1 sm:mr-2"></i>
                            <span class="hidden sm:inline">Check All</span>
                            <span class="sm:hidden">Check</span>
                        </button>
                        <button onclick="toggleDebugConsole()" 
                                class="inline-flex items-center px-3 py-2 border border-gray-300 dark:border-gray-600 shadow-sm text-sm font-medium rounded-lg text-gray-600 dark:text-gray-300 bg-white dark:bg-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 transition-colors duration-200 whitespace-nowrap">
                            <i class="fas fa-terminal mr-1 sm:mr-2"></i>
                            <span class="hidden sm:inline">Debug</span>
                            <span class="sm:hidden">Debug</span>
                        </button>
                    </div>
                </div>
            </div>
            <div id="certificatesList" class="divide-y divide-gray-200 dark:divide-gray-700">
                <!-- Certificates will be loaded here -->
            </div>
        </div>
    </div>

    <!-- Loading Modal -->
    <div id="loadingModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden flex items-center justify-center z-50">
        <div class="bg-white dark:bg-gray-800 rounded-lg p-6 m-4 max-w-md w-full">
            <div class="text-center">
                <div class="relative">
                    <div class="animate-spin rounded-full h-16 w-16 border-4 border-gray-200 dark:border-gray-600 border-t-primary mx-auto"></div>
                    <div class="absolute inset-0 flex items-center justify-center">
                        <i class="fas fa-certificate text-primary text-lg"></i>
                    </div>
                </div>
                <h3 class="mt-4 text-lg font-medium text-gray-900 dark:text-white" id="loadingTitle">Processing Certificate...</h3>
                <p class="mt-2 text-sm text-gray-600 dark:text-gray-300" id="loadingMessage">This may take a few minutes</p>
                <div class="mt-4 bg-gray-200 dark:bg-gray-600 rounded-full h-2">
                    <div class="bg-primary h-2 rounded-full transition-all duration-1000" id="progressBar" style="width: 0%"></div>
                </div>
                <p class="mt-2 text-xs text-gray-500 dark:text-gray-400">Do not close this window</p>
            </div>
        </div>
    </div>

    <!-- Curl Command Modal -->
    <div id="curlModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden flex items-center justify-center z-50">
        <div class="bg-white rounded-lg p-6 m-4 max-w-2xl w-full max-h-96 overflow-y-auto">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-medium text-gray-900">
                    <i class="fas fa-code mr-2"></i>
                    Automation curl Command
                </h3>
                <button onclick="closeCurlModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Copy this command:</label>
                    <div class="bg-gray-100 p-3 rounded-md font-mono text-sm">
                        <code id="curlCommandText"></code>
                    </div>
                    <button onclick="copyFromModal()" class="mt-2 inline-flex items-center px-3 py-1 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                        <i class="fas fa-copy mr-1"></i>
                        Copy Command
                    </button>
                </div>
                
                <div class="text-sm text-gray-600">
                    <p class="mb-2"><strong>Note:</strong> Replace <code>YOUR_API_TOKEN</code> with your actual API bearer token.</p>
                    <p class="mb-2"><strong>Usage:</strong> This downloads a ZIP file containing cert.pem, chain.pem, fullchain.pem, and privkey.pem</p>
                    <p><strong>Example extraction:</strong></p>
                    <div class="bg-gray-100 p-2 rounded text-xs font-mono mt-1">
                        <code>unzip domain.com-tls.zip -d /etc/ssl/certs/domain.com/</code>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Success/Error Messages -->
    <div id="messages" class="fixed top-4 right-4 z-50"></div>

    <!-- Debug Console -->
    <div id="debugConsole" class="fixed bottom-4 left-4 right-4 bg-black text-green-400 font-mono text-xs rounded-lg shadow-lg border border-gray-600 hidden z-40">
        <div class="flex items-center justify-between p-3 border-b border-gray-600">
            <div class="flex items-center space-x-2">
                <i class="fas fa-terminal text-green-400"></i>
                <span class="text-white font-semibold">Deployment Check Debug Console</span>
                <span class="text-gray-400 text-xs">| Cache: <span id="debug-cache-info">Loading...</span></span>
            </div>
            <div class="flex items-center space-x-2">
                <button onclick="showCacheStats()" class="text-blue-400 hover:text-blue-300" title="Show cache stats">
                    <i class="fas fa-database"></i>
                </button>
                <button onclick="invalidateAllCache()" class="text-orange-400 hover:text-orange-300" title="Clear cache">
                    <i class="fas fa-trash"></i>
                </button>
                <button onclick="clearDebugConsole()" class="text-yellow-400 hover:text-yellow-300" title="Clear console">
                    <i class="fas fa-eraser"></i>
                </button>
                <button onclick="toggleDebugConsole()" class="text-gray-400 hover:text-white" title="Close console">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        </div>
        <div id="debugOutput" class="p-3 max-h-64 overflow-y-auto">
            <div class="text-gray-500">Debug console ready. Click "Check All" to see deployment check logs...</div>
        </div>
    </div>

    <script>
        // API Configuration
        const API_TOKEN = '{{ api_token }}';
        const API_HEADERS = {
            'Authorization': `Bearer ${API_TOKEN}`,
            'Content-Type': 'application/json'
        };

        // Show enhanced loading modal with progress
        function showLoadingModal(title = 'Processing Certificate...', message = 'This may take a few minutes') {
            const modal = document.getElementById('loadingModal');
            document.getElementById('loadingTitle').textContent = title;
            document.getElementById('loadingMessage').textContent = message;
            document.getElementById('progressBar').style.width = '0%';
            modal.classList.remove('hidden');
            
            // Simulate progress for better UX
            let progress = 0;
            const progressInterval = setInterval(() => {
                progress += Math.random() * 15;
                if (progress > 90) progress = 90; // Don't complete until actual completion
                document.getElementById('progressBar').style.width = progress + '%';
            }, 1000);
            
            return progressInterval;
        }
        
        // Hide loading modal and complete progress
        function hideLoadingModal(progressInterval) {
            document.getElementById('progressBar').style.width = '100%';
            setTimeout(() => {
                document.getElementById('loadingModal').classList.add('hidden');
                if (progressInterval) clearInterval(progressInterval);
            }, 500);
        }

        // Show message function with improved styling
        function showMessage(message, type = 'success') {
            const messagesContainer = document.getElementById('messages');
            const messageDiv = document.createElement('div');
            
            const typeStyles = {
                'success': 'bg-green-50 text-green-800 border border-green-200',
                'error': 'bg-red-50 text-red-800 border border-red-200',
                'info': 'bg-blue-50 text-blue-800 border border-blue-200',
                'warning': 'bg-yellow-50 text-yellow-800 border border-yellow-200'
            };
            
            const typeIcons = {
                'success': 'fa-check-circle',
                'error': 'fa-exclamation-circle',
                'info': 'fa-info-circle',
                'warning': 'fa-exclamation-triangle'
            };
            
            messageDiv.className = `mb-4 p-4 rounded-lg shadow-lg max-w-sm transform transition-all duration-300 ease-in-out ${typeStyles[type] || typeStyles.success}`;
            messageDiv.innerHTML = `
                <div class="flex items-start">
                    <div class="flex-shrink-0">
                        <i class="fas ${typeIcons[type] || typeIcons.success} mt-0.5"></i>
                    </div>
                    <div class="ml-3 flex-1">
                        <p class="text-sm font-medium">${message}</p>
                    </div>
                    <button onclick="this.parentElement.parentElement.remove()" class="ml-2 flex-shrink-0 text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times text-xs"></i>
                    </button>
                </div>
            `;
            
            // Add animation
            messageDiv.style.transform = 'translateX(100%)';
            messageDiv.style.opacity = '0';
            messagesContainer.appendChild(messageDiv);
            
            // Trigger animation
            setTimeout(() => {
                messageDiv.style.transform = 'translateX(0)';
                messageDiv.style.opacity = '1';
            }, 10);
            
            // Auto-remove after 5 seconds
            setTimeout(() => {
                if (messageDiv.parentNode) {
                    messageDiv.style.transform = 'translateX(100%)';
                    messageDiv.style.opacity = '0';
                    setTimeout(() => messageDiv.remove(), 300);
                }
            }, 5000);
        }

        // Clear filters function
        function clearFilters() {
            document.getElementById('certificateSearch').value = '';
            document.getElementById('statusFilter').value = 'all';
            filterCertificates();
        }

        // Update statistics cards with deployment info
        function updateStats(certificates) {
            // Ensure certificates is an array
            if (!Array.isArray(certificates)) {
                console.error('[DEPLOYMENT CHECK] updateStats called with non-array:', certificates);
                certificates = []; // Fallback to empty array
            }
            
            const total = certificates.length;
            const valid = certificates.filter(cert => cert.exists && cert.days_until_expiry > 30).length;
            const expiring = certificates.filter(cert => cert.exists && cert.days_until_expiry > 0 && cert.days_until_expiry <= 30).length;
            const expired = certificates.filter(cert => cert.exists && cert.days_until_expiry <= 0).length;
            
            const statsContainer = document.getElementById('statsCards');
            statsContainer.innerHTML = `
                <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm rounded-lg border border-gray-200 dark:border-gray-700 hover:shadow-md transition-shadow duration-200">
                    <div class="p-6">
                        <div class="flex items-center">
                            <div class="flex-shrink-0">
                                <div class="w-12 h-12 bg-blue-100 dark:bg-blue-900/30 rounded-lg flex items-center justify-center">
                                    <i class="fas fa-certificate text-blue-600 dark:text-blue-400 text-xl"></i>
                                </div>
                            </div>
                            <div class="ml-4 flex-1">
                                <p class="text-sm font-medium text-gray-600 dark:text-gray-400">Total Certificates</p>
                                <p class="text-2xl font-bold text-gray-900 dark:text-white">${total}</p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm rounded-lg border border-gray-200 dark:border-gray-700 hover:shadow-md transition-shadow duration-200">
                    <div class="p-6">
                        <div class="flex items-center">
                            <div class="flex-shrink-0">
                                <div class="w-12 h-12 bg-green-100 dark:bg-green-900/30 rounded-lg flex items-center justify-center">
                                    <i class="fas fa-check-circle text-green-600 dark:text-green-400 text-xl"></i>
                                </div>
                            </div>
                            <div class="ml-4 flex-1">
                                <p class="text-sm font-medium text-gray-600 dark:text-gray-400">Valid</p>
                                <p class="text-2xl font-bold text-green-600 dark:text-green-400">${valid}</p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm rounded-lg border border-gray-200 dark:border-gray-700 hover:shadow-md transition-shadow duration-200">
                    <div class="p-6">
                        <div class="flex items-center">
                            <div class="flex-shrink-0">
                                <div class="w-12 h-12 bg-yellow-100 dark:bg-yellow-900/30 rounded-lg flex items-center justify-center">
                                    <i class="fas fa-exclamation-triangle text-yellow-600 dark:text-yellow-400 text-xl"></i>
                                </div>
                            </div>
                            <div class="ml-4 flex-1">
                                <p class="text-sm font-medium text-gray-600 dark:text-gray-400">Expiring Soon</p>
                                <p class="text-2xl font-bold text-yellow-600 dark:text-yellow-400">${expiring}</p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm rounded-lg border border-gray-200 dark:border-gray-700 hover:shadow-md transition-shadow duration-200">
                    <div class="p-6">
                        <div class="flex items-center">
                            <div class="flex-shrink-0">
                                <div class="w-12 h-12 bg-indigo-100 dark:bg-indigo-900/30 rounded-lg flex items-center justify-center">
                                    <i class="fas fa-globe text-indigo-600 dark:text-indigo-400 text-xl"></i>
                                </div>
                            </div>
                            <div class="ml-4 flex-1">
                                <p class="text-sm font-medium text-gray-600 dark:text-gray-400">Deployment</p>
                                <p class="text-2xl font-bold text-indigo-600 dark:text-indigo-400" id="deploymentCount">--</p>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }

        // Deployment Status Cache System
        class DeploymentCache {
            constructor() {
                this.cache = new Map();
                this.defaultTTL = 300000; // 5 minutes default
                this.loadSettings();
            }

            loadSettings() {
                try {
                    const savedSettings = localStorage.getItem('deployment-cache-settings');
                    if (savedSettings) {
                        const settings = JSON.parse(savedSettings);
                        this.defaultTTL = settings.ttl || this.defaultTTL;
                        console.log(`[DEPLOYMENT CACHE] Loaded settings: TTL ${this.defaultTTL}ms`);
                    }
                } catch (error) {
                    console.warn('[DEPLOYMENT CACHE] Failed to load settings:', error);
                }
            }

            saveSettings(ttl) {
                try {
                    this.defaultTTL = ttl;
                    localStorage.setItem('deployment-cache-settings', JSON.stringify({ ttl }));
                    console.log(`[DEPLOYMENT CACHE] Saved settings: TTL ${ttl}ms`);
                } catch (error) {
                    console.error('[DEPLOYMENT CACHE] Failed to save settings:', error);
                }
            }

            set(domain, result) {
                const timestamp = Date.now();
                this.cache.set(domain, {
                    result,
                    timestamp,
                    ttl: this.defaultTTL
                });
                console.log(`[DEPLOYMENT CACHE] Cached result for ${domain}, expires in ${this.defaultTTL}ms`);
            }

            get(domain) {
                const cached = this.cache.get(domain);
                if (!cached) return null;

                const now = Date.now();
                const isExpired = (now - cached.timestamp) > cached.ttl;
                
                if (isExpired) {
                    this.cache.delete(domain);
                    console.log(`[DEPLOYMENT CACHE] Cache expired for ${domain}`);
                    return null;
                }

                const remainingTime = cached.ttl - (now - cached.timestamp);
                console.log(`[DEPLOYMENT CACHE] Cache hit for ${domain}, expires in ${Math.round(remainingTime/1000)}s`);
                return cached.result;
            }

            invalidate(domain) {
                if (this.cache.delete(domain)) {
                    console.log(`[DEPLOYMENT CACHE] Invalidated cache for ${domain}`);
                }
            }

            clear() {
                const size = this.cache.size;
                this.cache.clear();
                console.log(`[DEPLOYMENT CACHE] Cleared ${size} cached entries`);
            }

            getStatus() {
                const now = Date.now();
                const entries = Array.from(this.cache.entries()).map(([domain, data]) => ({
                    domain,
                    age: Math.round((now - data.timestamp) / 1000),
                    remaining: Math.round((data.ttl - (now - data.timestamp)) / 1000),
                    status: data.result.deployed ? 'deployed' : 'not-deployed'
                }));
                return {
                    totalEntries: this.cache.size,
                    ttl: Math.round(this.defaultTTL / 1000),
                    entries
                };
            }
        }

        // Initialize cache
        const deploymentCache = new DeploymentCache();

        // Global variable to store all certificates
        let allCertificates = [];

        // Filter and search certificates
        function filterCertificates() {
            const searchTerm = document.getElementById('certificateSearch').value.toLowerCase();
            const statusFilter = document.getElementById('statusFilter').value;
            
            // Ensure allCertificates is an array
            if (!Array.isArray(allCertificates)) {
                console.error('[DEPLOYMENT CHECK] allCertificates is not an array:', allCertificates);
                allCertificates = [];
            }
            
            const filteredCerts = allCertificates.filter(cert => {
                // Search filter
                const matchesSearch = cert.domain.toLowerCase().includes(searchTerm);
                
                // Status filter
                let matchesStatus = true;
                if (statusFilter !== 'all') {
                    const isExpired = cert.exists && cert.days_until_expiry <= 0;
                    const isExpiringSoon = cert.exists && cert.days_until_expiry > 0 && cert.days_until_expiry <= 30;
                    const isValid = cert.exists && cert.days_until_expiry > 30;
                    
                    switch (statusFilter) {
                        case 'valid':
                            matchesStatus = isValid;
                            break;
                        case 'expiring':
                            matchesStatus = isExpiringSoon;
                            break;
                        case 'expired':
                            matchesStatus = isExpired;
                            break;
                    }
                }
                
                return matchesSearch && matchesStatus;
            });
            
            displayCertificates(filteredCerts);
        }

        // Display certificates  
        function displayCertificates(certificates) {
            const container = document.getElementById('certificatesList');
            
            // Ensure certificates is an array
            if (!Array.isArray(certificates)) {
                console.error('[DEPLOYMENT CHECK] displayCertificates called with non-array:', certificates);
                certificates = []; // Fallback to empty array
            }
            
            if (certificates.length === 0) {
                const isFiltered = document.getElementById('certificateSearch').value || 
                                 document.getElementById('statusFilter').value !== 'all';
                
                container.innerHTML = `
                    <div class="px-6 py-12 text-center">
                        <div class="mx-auto max-w-sm">
                            <div class="mx-auto h-16 w-16 flex items-center justify-center bg-gray-100 rounded-full mb-4">
                                <i class="fas ${isFiltered ? 'fa-search' : 'fa-certificate'} text-gray-400 text-2xl"></i>
                            </div>
                            <h3 class="text-lg font-medium text-gray-900 dark:text-gray-100 mb-2">
                                ${isFiltered ? 'No matching certificates' : 'No certificates yet'}
                            </h3>
                            <p class="text-gray-500 dark:text-gray-400 mb-6">
                                ${isFiltered ? 
                                    'Try adjusting your search criteria or filters to find certificates.' : 
                                    'Get started by creating your first SSL certificate above.'
                                }
                            </p>
                            ${!isFiltered ? `
                                <button onclick="document.getElementById('domain').focus()" 
                                        class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-primary hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary transition-colors duration-200">
                                    <i class="fas fa-plus mr-2"></i>
                                    Create Certificate
                                </button>
                            ` : `
                                <button onclick="clearFilters()" 
                                        class="inline-flex items-center px-4 py-2 border border-gray-300 dark:border-gray-600 shadow-sm text-sm font-medium rounded-md text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary transition-colors duration-200">
                                    <i class="fas fa-times mr-2"></i>
                                    Clear Filters
                                </button>
                            `}
                        </div>
                    </div>
                `;
                return;
            }
            
            container.innerHTML = certificates.map(cert => {
                if (!cert.exists) {
                    return `
                        <div class="px-6 py-4">
                            <div class="flex items-center justify-between">
                                <div>
                                    <h4 class="text-lg font-medium text-gray-900 dark:text-white">${cert.domain}</h4>
                                    <p class="text-sm text-red-600 dark:text-red-400">Certificate not found</p>
                                    ${cert.dns_provider ? `<p class="text-sm text-gray-500 dark:text-gray-400">DNS Provider: ${cert.dns_provider.charAt(0).toUpperCase() + cert.dns_provider.slice(1)}</p>` : ''}
                                </div>
                            </div>
                        </div>
                    `;
                }
                
                const expiryDate = new Date(cert.expiry_date);
                const isExpiringSoon = cert.days_until_expiry <= 30;
                const isExpired = cert.days_until_expiry <= 0;
                
                // Check if we have cached deployment status for this domain
                const cachedStatus = deploymentCache.get(cert.domain);
                let deploymentHtml = '';
                
                if (cachedStatus) {
                    // Use cached deployment status
                    const isDeployed = cachedStatus.deployed;
                    const isReachable = cachedStatus.reachable;
                    const certificateMatch = cachedStatus.certificate_match;
                    
                    let statusClass, statusIcon, statusText;
                    
                    if (isDeployed && certificateMatch) {
                        statusClass = 'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-400';
                        statusIcon = 'fa-check-circle';
                        statusText = 'Deployed';
                    } else if (isReachable && !certificateMatch) {
                        statusClass = 'bg-yellow-100 dark:bg-yellow-900/30 text-yellow-800 dark:text-yellow-400';
                        statusIcon = 'fa-exclamation-triangle';
                        statusText = 'Wrong Cert';
                    } else if (!isReachable) {
                        statusClass = 'bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-400';
                        statusIcon = 'fa-times-circle';
                        statusText = 'Not Deployed';
                    } else {
                        statusClass = 'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300';
                        statusIcon = 'fa-question-circle';
                        statusText = 'Unknown';
                    }
                    
                    deploymentHtml = `
                        <span id="deployment-status-${cert.domain.replace(/\./g, '-')}" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${statusClass}">
                            <i class="fas ${statusIcon} mr-1"></i>
                            ${statusText}
                        </span>
                    `;
                } else {
                    // No cached status, show checking state
                    deploymentHtml = `
                        <span id="deployment-status-${cert.domain.replace(/\./g, '-')}" class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300">
                            <i class="fas fa-spinner fa-spin mr-1"></i>
                            Checking...
                        </span>
                    `;
                }
                
                return `
                    <div class="px-6 py-4 hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors duration-200">
                        <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between space-y-3 lg:space-y-0 lg:space-x-4">
                            <!-- Certificate Header Info -->
                            <div class="flex items-center space-x-3 min-w-0 flex-1">
                                <div class="flex-shrink-0">
                                    <div class="w-10 h-10 bg-blue-100 dark:bg-blue-900/30 rounded-lg flex items-center justify-center">
                                        <i class="fas fa-certificate text-blue-600 dark:text-blue-400"></i>
                                    </div>
                                </div>
                                <div class="min-w-0 flex-1">
                                    <h4 class="text-lg font-semibold text-gray-900 dark:text-white truncate">${cert.domain}</h4>
                                    <div class="flex flex-wrap items-center gap-2 mt-1">
                                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                                            isExpired ? 'bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-400' : 
                                            isExpiringSoon ? 'bg-yellow-100 dark:bg-yellow-900/30 text-yellow-800 dark:text-yellow-400' : 
                                            'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-400'
                                        }">
                                            <i class="fas ${isExpired ? 'fa-times-circle' : isExpiringSoon ? 'fa-exclamation-triangle' : 'fa-check-circle'} mr-1"></i>
                                            ${isExpired ? 'Expired' : isExpiringSoon ? 'Expiring Soon' : 'Valid'}
                                        </span>
                                        ${deploymentHtml}
                                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                                            isExpired ? 'bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-400' : 
                                            isExpiringSoon ? 'bg-yellow-100 dark:bg-yellow-900/30 text-yellow-800 dark:text-yellow-400' : 
                                            'bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-400'
                                        }" title="Certificate expires in ${cert.days_until_expiry} days">
                                            <i class="fas fa-clock mr-1"></i>
                                            ${cert.days_until_expiry} days
                                        </span>
                                        ${cert.dns_provider ? `
                                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-white dark:bg-gray-900 text-gray-900 dark:text-white" title="${cert.dns_provider.charAt(0).toUpperCase() + cert.dns_provider.slice(1)} DNS Provider">
                                            <i class="fas fa-server mr-1"></i>
                                            ${cert.dns_provider.charAt(0).toUpperCase() + cert.dns_provider.slice(1)}
                                        </span>
                                        ` : ''}
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Certificate Details (Compact) -->
                            <div class="flex flex-wrap items-center gap-4 lg:gap-6">
                            </div>
                            
                            <!-- Action Buttons (Compact) -->
                            <div class="flex flex-wrap items-center gap-2">
                                <button onclick="renewCertificate('${cert.domain}')" 
                                        class="inline-flex items-center px-3 py-1.5 border border-gray-300 dark:border-gray-600 shadow-sm text-xs font-medium rounded-md text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary transition-colors duration-200">
                                    <i class="fas fa-sync-alt mr-1 text-green-600"></i>
                                    Renew
                                </button>
                                <button onclick="downloadCertificate('${cert.domain}')" 
                                        class="inline-flex items-center px-3 py-1.5 border border-gray-300 dark:border-gray-600 shadow-sm text-xs font-medium rounded-md text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary transition-colors duration-200">
                                    <i class="fas fa-download mr-1 text-blue-600"></i>
                                    Download
                                </button>
                                <button onclick="copyCurlCommand('${cert.domain}')" 
                                        class="inline-flex items-center px-3 py-1.5 border border-blue-300 dark:border-blue-600 shadow-sm text-xs font-medium rounded-md text-blue-700 dark:text-blue-300 bg-blue-50 dark:bg-blue-900/30 hover:bg-blue-100 dark:hover:bg-blue-900/50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors duration-200">
                                    <i class="fas fa-code mr-1"></i>
                                    API
                                </button>
                            </div>
                        </div>
                        
                        <!-- Auto-renewal Notice (if needed) -->
                        ${cert.days_until_expiry > 0 && cert.days_until_expiry <= 30 ? `
                            <div class="mt-3 p-3 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-600 rounded-lg">
                                <div class="flex items-start space-x-2">
                                    <i class="fas fa-exclamation-triangle text-yellow-600 dark:text-yellow-400 mt-0.5"></i>
                                    <div class="text-sm text-yellow-800 dark:text-yellow-200">
                                        <p class="font-medium">Auto-renewal scheduled</p>
                                        <p class="mt-1">Certificate will be renewed automatically within ${Math.max(cert.days_until_expiry - 30, 0)} days</p>
                                    </div>
                                </div>
                            </div>
                        ` : ''}
                    </div>
                `;
            }).join('');
            
            // After displaying, trigger deployment checks only for certificates that don't have cached status
            setTimeout(() => {
                if (Array.isArray(certificates)) {
                    certificates.filter(cert => cert.exists).forEach(cert => {
                        if (!deploymentCache.get(cert.domain)) {
                            checkDeploymentStatus(cert.domain);
                        }
                    });
                }
            }, 100);
        }

        // Debug console functions
        function toggleDebugConsole() {
            const console = document.getElementById('debugConsole');
            console.classList.toggle('hidden');
        }

        function clearDebugConsole() {
            document.getElementById('debugOutput').innerHTML = '<div class="text-gray-500">Debug console cleared. Click "Check All" to see deployment check logs...</div>';
        }

        function addDebugLog(message, type = 'info') {
            const output = document.getElementById('debugOutput');
            const timestamp = new Date().toLocaleTimeString();
            const colors = {
                info: 'text-green-400',
                warn: 'text-yellow-400', 
                error: 'text-red-400',
                success: 'text-blue-400'
            };
            
            const logEntry = document.createElement('div');
            logEntry.className = `${colors[type] || colors.info} mb-1`;
            logEntry.innerHTML = `<span class="text-gray-500">[${timestamp}]</span> ${message}`;
            
            output.appendChild(logEntry);
            output.scrollTop = output.scrollHeight;
            
            // Keep only last 100 entries
            while (output.children.length > 100) {
                output.removeChild(output.firstChild);
            }
        }

        // Override console methods to also log to debug panel
        const originalConsoleLog = console.log;
        const originalConsoleWarn = console.warn;
        const originalConsoleError = console.error;

        console.log = function(...args) {
            originalConsoleLog.apply(console, args);
            if (args[0] && args[0].includes && args[0].includes('[DEPLOYMENT CHECK]')) {
                addDebugLog(args.join(' '), 'info');
            }
        };

        console.warn = function(...args) {
            originalConsoleWarn.apply(console, args);
            if (args[0] && args[0].includes && args[0].includes('[DEPLOYMENT CHECK]')) {
                addDebugLog(args.join(' '), 'warn');
            }
        };

        console.error = function(...args) {
            originalConsoleError.apply(console, args);
            if (args[0] && args[0].includes && args[0].includes('[DEPLOYMENT CHECK]')) {
                addDebugLog(args.join(' '), 'error');
            }
        };

        // Cache management functions
        function showCacheStats() {
            const stats = deploymentCache.getStatus();
            const ttlMinutes = Math.round(stats.ttl / 60);
            const ttlHours = Math.round(stats.ttl / 3600);
            
            let ttlDisplay = `${stats.ttl}s`;
            if (ttlHours >= 1) {
                ttlDisplay = `${ttlHours}h`;
            } else if (ttlMinutes >= 1) {
                ttlDisplay = `${ttlMinutes}m`;
            }
            
            addDebugLog(`=== CACHE STATISTICS ===`, 'info');
            addDebugLog(`Total entries: ${stats.totalEntries}`, 'info');
            addDebugLog(`TTL: ${ttlDisplay} (${stats.ttl} seconds)`, 'info');
            
            if (stats.entries.length > 0) {
                addDebugLog(`Recent entries:`, 'info');
                stats.entries.slice(0, 5).forEach(entry => {
                    addDebugLog(`  ${entry.domain}: ${entry.status} (${entry.remaining}s remaining)`, 'info');
                });
                if (stats.entries.length > 5) {
                    addDebugLog(`  ... and ${stats.entries.length - 5} more entries`, 'info');
                }
            } else {
                addDebugLog(`No cached entries`, 'warn');
            }
            addDebugLog(`========================`, 'info');
        }

        function invalidateAllCache() {
            if (confirm('Clear all cached deployment status data? This will force a fresh check for all certificates.')) {
                deploymentCache.clear();
                addDebugLog('All cache entries cleared by user request', 'warn');
                updateCacheInfo();
                
                // Ensure allCertificates is an array before checking
                if (Array.isArray(allCertificates) && allCertificates.length > 0) {
                    addDebugLog('Re-checking all certificates after cache clear...', 'info');
                    setTimeout(() => {
                        const existingCerts = allCertificates.filter(cert => cert.exists);
                        existingCerts.forEach(cert => checkDeploymentStatus(cert.domain));
                    }, 1000);
                }
            }
        }

        function updateCacheInfo() {
            const stats = deploymentCache.getStatus();
            const ttlMinutes = Math.round(stats.ttl / 60);
            const infoElement = document.getElementById('debug-cache-info');
            
            if (infoElement) {
                let ttlDisplay = `${stats.ttl}s`;
                if (ttlMinutes >= 1) {
                    ttlDisplay = `${ttlMinutes}m`;
                }
                infoElement.textContent = `${stats.totalEntries} entries, TTL ${ttlDisplay}`;
            }
        }

        // Update cache info periodically
        setInterval(updateCacheInfo, 10000); // Update every 10 seconds

        // Update deployment statistics with better counting
        function updateDeploymentStats() {
            console.log('[DEPLOYMENT CHECK] Updating deployment statistics');
            
            // Ensure allCertificates is an array
            if (!Array.isArray(allCertificates)) {
                console.error('[DEPLOYMENT CHECK] allCertificates is not an array:', allCertificates);
                allCertificates = [];
            }
            
            const deployedCount = allCertificates.filter(cert => {
                if (!cert.exists) return false;
                const statusElement = document.getElementById(`deployment-status-${cert.domain.replace(/\./g, '-')}`);
                const isDeployed = statusElement && statusElement.textContent.includes('Deployed');
                
                if (isDeployed) {
                    console.log(`[DEPLOYMENT CHECK] ${cert.domain} counted as deployed`);
                }
                
                return isDeployed;
            }).length;
            
            const deploymentCountElement = document.getElementById('deploymentCount');
            if (deploymentCountElement) {
                deploymentCountElement.textContent = deployedCount;
                console.log(`[DEPLOYMENT CHECK] Updated statistics: ${deployedCount} certificates deployed`);
            }
            
            addDebugLog(`Statistics updated: ${deployedCount} certificates actively deployed`, 'success');
        }

        // Check deployment status for all certificates
        async function checkAllDeploymentStatuses() {
            const button = event.target;
            const originalText = button.innerHTML;
            button.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Checking...';
            button.disabled = true;
            
            console.log('[DEPLOYMENT CHECK] Starting bulk deployment check for all certificates');
            
            try {
                // Ensure allCertificates is an array
                if (!Array.isArray(allCertificates)) {
                    console.error('[DEPLOYMENT CHECK] allCertificates is not an array:', allCertificates);
                    allCertificates = [];
                }
                
                const certificatesToCheck = allCertificates.filter(cert => cert.exists);
                console.log(`[DEPLOYMENT CHECK] Found ${certificatesToCheck.length} certificates to check`);
                
                if (certificatesToCheck.length === 0) {
                    showMessage('No certificates found to check', 'info');
                    return;
                }
                
                // Update button to show progress
                let completed = 0;
                const total = certificatesToCheck.length;
                
                const updateProgress = () => {
                    const percentage = Math.round((completed / total) * 100);
                    button.innerHTML = `<i class="fas fa-spinner fa-spin mr-2"></i>Checking... ${completed}/${total} (${percentage}%)`;
                };
                
                // Check certificates in batches to avoid overwhelming the server
                const batchSize = 3;
                const batches = [];
                for (let i = 0; i < certificatesToCheck.length; i += batchSize) {
                    batches.push(certificatesToCheck.slice(i, i + batchSize));
                }
                
                console.log(`[DEPLOYMENT CHECK] Processing ${batches.length} batches of ${batchSize} certificates each`);
                
                for (const batch of batches) {
                    const batchPromises = batch.map(async (cert) => {
                        try {
                            await checkDeploymentStatus(cert.domain);
                            completed++;
                            updateProgress();
                            console.log(`[DEPLOYMENT CHECK] Completed check for ${cert.domain} (${completed}/${total})`);
                        } catch (error) {
                            console.error(`[DEPLOYMENT CHECK] Failed to check ${cert.domain}:`, error);
                            completed++;
                            updateProgress();
                        }
                    });
                    
                    await Promise.all(batchPromises);
                    
                    // Small delay between batches to be nice to the server
                    if (batches.indexOf(batch) < batches.length - 1) {
                        await new Promise(resolve => setTimeout(resolve, 500));
                    }
                }
                
                updateDeploymentStats();
                console.log('[DEPLOYMENT CHECK] Bulk deployment check completed successfully');
                showMessage(`Deployment status updated for ${total} certificates`, 'success');
                
            } catch (error) {
                console.error('[DEPLOYMENT CHECK] Bulk deployment check failed:', error);
                showMessage('Failed to check deployment status for some certificates', 'error');
            } finally {
                button.innerHTML = originalText;
                button.disabled = false;
                console.log('[DEPLOYMENT CHECK] Bulk deployment check finished');
            }
        }

        // Check deployment status for a specific domain
        async function checkDeploymentStatus(domain) {
            const statusElement = document.getElementById(`deployment-status-${domain.replace(/\./g, '-')}`);
            const textElement = document.getElementById(`deployment-text-${domain.replace(/\./g, '-')}`);
            
            if (!statusElement) {
                console.warn(`[DEPLOYMENT CHECK] Status element not found for domain: ${domain}`);
                return;
            }
            
            console.log(`[DEPLOYMENT CHECK] Starting check for: ${domain}`);
            
            // Check cache first
            const cachedResult = deploymentCache.get(domain);
            if (cachedResult) {
                console.log(`[DEPLOYMENT CHECK] Using cached result for ${domain}`);
                updateDeploymentUI(domain, cachedResult, statusElement);
                return;
            }
            
            // Update UI to show checking state
            statusElement.className = 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-600';
            statusElement.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>Checking...';
            if (textElement) {
                textElement.textContent = 'Checking...';
                textElement.className = 'text-sm font-medium text-blue-600';
            }
            
            try {
                // Method 1: Try dedicated deployment status endpoint (real API)
                console.log(`[DEPLOYMENT CHECK] Method 1: Trying API endpoint for ${domain}`);
                let result = null;
                let apiSuccess = false;
                
                try {
                    const response = await fetch(`/api/certificates/${domain}/deployment-status`, {
                        method: 'GET',
                        headers: API_HEADERS
                    });
                    
                    if (response.ok) {
                        result = await response.json();
                        apiSuccess = true;
                        console.log(`[DEPLOYMENT CHECK] API response for ${domain}:`, result);
                    } else {
                        console.warn(`[DEPLOYMENT CHECK] API endpoint failed for ${domain}:`, response.status, response.statusText);
                    }
                } catch (apiError) {
                    console.warn(`[DEPLOYMENT CHECK] API endpoint error for ${domain}:`, apiError.message);
                }
                
                // Method 2: Fallback to browser-based certificate check
                if (!apiSuccess) {
                    console.log(`[DEPLOYMENT CHECK] Method 2: Fallback certificate check for ${domain}`);
                    result = await checkDeploymentViaBrowser(domain);
                }
                
                // Method 3: Final fallback - only if absolutely necessary (disabled now that we have real API)
                if (!result) {
                    console.log(`[DEPLOYMENT CHECK] Method 3: No fallback available for ${domain}`);
                    result = {
                        deployed: false,
                        reachable: false,
                        certificate_match: false,
                        method: 'unavailable',
                        error: 'all_methods_failed',
                        timestamp: new Date().toISOString()
                    };
                }
                
                // Cache the result
                deploymentCache.set(domain, result);
                
                // Update UI based on result
                updateDeploymentUI(domain, result, statusElement);
                
            } catch (error) {
                console.error(`[DEPLOYMENT CHECK] Fatal error for ${domain}:`, error);
                // Error occurred during check
                statusElement.className = 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300';
                statusElement.innerHTML = '<i class="fas fa-question-circle mr-1"></i>Error';
            }
        }

        // Browser-based certificate check fallback
        async function checkDeploymentViaBrowser(domain) {
            try {
                console.log(`[DEPLOYMENT CHECK] Browser check: Testing HTTPS for ${domain}`);
                
                // Try to fetch the SSL certificate info via a simple request
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), 10000); // 10 second timeout
                
                const response = await fetch(`https://${domain}`, {
                    method: 'HEAD',
                    mode: 'no-cors', // Avoid CORS issues
                    signal: controller.signal
                });
                
                clearTimeout(timeoutId);
                
                // If we get here, the domain is reachable with HTTPS
                console.log(`[DEPLOYMENT CHECK] Browser check: ${domain} is reachable via HTTPS`);
                
                return {
                    deployed: true, // We can't verify exact certificate match via browser
                    reachable: true,
                    certificate_match: null, // Unknown via browser method
                    method: 'browser-fallback',
                    timestamp: new Date().toISOString()
                };
                
            } catch (browserError) {
                console.warn(`[DEPLOYMENT CHECK] Browser check failed for ${domain}:`, browserError.message);
                
                if (browserError.name === 'AbortError') {
                    return {
                        deployed: false,
                        reachable: false,
                        certificate_match: false,
                        method: 'browser-fallback',
                        error: 'timeout',
                        timestamp: new Date().toISOString()
                    };
                }
                
                return null; // Let it fall through to simulation
            }
        }

        // Update deployment UI based on check result
        function updateDeploymentUI(domain, result, statusElement) {
            console.log(`[DEPLOYMENT CHECK] Updating UI for ${domain}:`, result);
            
            const textElement = document.getElementById(`deployment-text-${domain.replace(/\./g, '-')}`);
            
            if (result.deployed && result.certificate_match !== false) {
                // Certificate is deployed and matches (or match unknown but deployed)
                statusElement.className = 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 dark:bg-green-900/30 text-green-800 dark:text-green-400';
                statusElement.innerHTML = '<i class="fas fa-check-circle mr-1"></i>Deployed';
                if (textElement) {
                    textElement.textContent = 'Active';
                    textElement.className = 'text-sm font-medium text-green-600 dark:text-green-400';
                }
                console.log(`[DEPLOYMENT CHECK] ${domain}: Status set to DEPLOYED`);
                
            } else if (result.reachable && result.certificate_match === false) {
                // Domain is reachable but certificate doesn't match
                statusElement.className = 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 dark:bg-yellow-900/30 text-yellow-800 dark:text-yellow-400';
                statusElement.innerHTML = '<i class="fas fa-exclamation-triangle mr-1"></i>Mismatch';
                if (textElement) {
                    textElement.textContent = 'Mismatch';
                    textElement.className = 'text-sm font-medium text-yellow-600 dark:text-yellow-400';
                }
                console.log(`[DEPLOYMENT CHECK] ${domain}: Status set to MISMATCH`);
                
            } else if (result.reachable) {
                // Domain is reachable but certificate status unknown
                statusElement.className = 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-400';
                statusElement.innerHTML = '<i class="fas fa-info-circle mr-1"></i>Unknown';
                if (textElement) {
                    textElement.textContent = 'Unknown';
                    textElement.className = 'text-sm font-medium text-blue-600 dark:text-blue-400';
                }
                console.log(`[DEPLOYMENT CHECK] ${domain}: Status set to UNKNOWN`);
                
            } else {
                // Domain is not reachable
                statusElement.className = 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-400';
                statusElement.innerHTML = '<i class="fas fa-times-circle mr-1"></i>Unreachable';
                if (textElement) {
                    textElement.textContent = 'Unreachable';
                    textElement.className = 'text-sm font-medium text-red-600 dark:text-red-400';
                }
                console.log(`[DEPLOYMENT CHECK] ${domain}: Status set to UNREACHABLE`);
            }
            
            // Add method info to title for debugging
            if (result.method) {
                statusElement.title = `Checked via: ${result.method} at ${result.timestamp}`;
                if (textElement) {
                    textElement.title = statusElement.title;
                }
            }
        }

        // Load certificates with deployment status
        async function loadCertificates() {
            console.log('[DEPLOYMENT CHECK] Loading certificates...');
            addDebugLog('Loading certificates from API...', 'info');
            
            try {
                const response = await fetch('/api/certificates', {
                    headers: API_HEADERS
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const certificates = await response.json();
                
                // Check if the response is an error object
                if (certificates && certificates.error) {
                    throw new Error(`API Error: ${certificates.error} (${certificates.code || 'unknown'})`);
                }
                
                // Ensure certificates is an array
                if (!Array.isArray(certificates)) {
                    console.error('[DEPLOYMENT CHECK] API returned non-array response:', certificates);
                    addDebugLog(`API returned invalid response: ${JSON.stringify(certificates)}`, 'error');
                    throw new Error('Invalid API response: expected array of certificates');
                }
                
                console.log(`[DEPLOYMENT CHECK] Loaded ${certificates.length} certificates`);
                addDebugLog(`Loaded ${certificates.length} certificates successfully`, 'success');
                
                allCertificates = certificates;
                updateStats(certificates);
                displayCertificates(certificates);
                
                // Check deployment status for all certificates after a short delay
                console.log('[DEPLOYMENT CHECK] Scheduling automatic deployment checks...');
                addDebugLog('Scheduling automatic deployment status checks...', 'info');
                
                setTimeout(async () => {
                    console.log('[DEPLOYMENT CHECK] Starting automatic deployment checks');
                    addDebugLog('Starting automatic deployment status checks for all certificates', 'info');
                    
                    const existingCerts = certificates.filter(cert => cert.exists);
                    if (existingCerts.length > 0) {
                        // Check certificates individually with batching
                        const promises = existingCerts.map(cert => checkDeploymentStatus(cert.domain));
                        await Promise.all(promises);
                        updateDeploymentStats();
                        addDebugLog(`Automatic deployment check completed for ${existingCerts.length} certificates`, 'success');
                    } else {
                        addDebugLog('No certificates with valid status found to check', 'warn');
                    }
                }, 1500);
                
            } catch (error) {
                console.error('[DEPLOYMENT CHECK] Failed to load certificates:', error);
                addDebugLog(`Failed to load certificates: ${error.message}`, 'error');
                
                // Initialize with empty array to prevent further errors
                allCertificates = [];
                updateStats([]);
                displayCertificates([]);
                
                // Show appropriate error message
                if (error.message.includes('401') || error.message.includes('Unauthorized')) {
                    showMessage('Authentication failed. Please check your API token.', 'error');
                } else if (error.message.includes('403') || error.message.includes('Forbidden')) {
                    showMessage('Access denied. Please check your permissions.', 'error');
                } else {
                    showMessage('Failed to load certificates. Please try again.', 'error');
                }
            }
        }

        // Listen for cache settings updates from settings page
        function setupCacheSettingsListener() {
            let lastUpdate = localStorage.getItem('cache-settings-updated');
            let lastClearSignal = localStorage.getItem('clear-deployment-cache');
            
            setInterval(() => {
                // Check for settings updates
                const currentUpdate = localStorage.getItem('cache-settings-updated');
                if (currentUpdate && currentUpdate !== lastUpdate) {
                    console.log('[DEPLOYMENT CACHE] Settings updated, reloading cache configuration');
                    deploymentCache.loadSettings();
                    addDebugLog('Cache settings updated from settings page', 'info');
                    lastUpdate = currentUpdate;
                }
                
                // Check for cache clear signals
                const currentClearSignal = localStorage.getItem('clear-deployment-cache');
                if (currentClearSignal && currentClearSignal !== lastClearSignal) {
                    console.log('[DEPLOYMENT CACHE] Cache clear requested');
                    deploymentCache.clear();
                    addDebugLog('Deployment cache cleared by admin request', 'warn');
                    // Re-check all certificates
                    setTimeout(() => {
                        if (Array.isArray(allCertificates) && allCertificates.length > 0) {
                            addDebugLog('Re-checking all certificates after cache clear...', 'info');
                            const existingCerts = allCertificates.filter(cert => cert.exists);
                            existingCerts.forEach(cert => checkDeploymentStatus(cert.domain));
                        }
                    }, 1000);
                    lastClearSignal = currentClearSignal;
                }
            }, 2000); // Check every 2 seconds
        }

        // Multi-account support functions
        let providerAccounts = {};

        async function loadProviderAccounts() {
            const providers = ['cloudflare', 'route53', 'digitalocean', 'azure', 'google', 'powerdns', 'rfc2136'];
            
            for (const provider of providers) {
                try {
                    const response = await fetch(`/api/settings/dns-providers/${provider}/accounts`, {
                        headers: API_HEADERS
                    });
                    
                    if (response.ok) {
                        const data = await response.json();
                        // Convert accounts object to array for compatibility
                        const accounts = data.accounts || {};
                        const accountsArray = Object.keys(accounts).map(accountId => ({
                            account_id: accountId,
                            ...accounts[accountId]
                        }));
                        providerAccounts[provider] = accountsArray;
                    }
                } catch (error) {
                    console.log(`No accounts found for ${provider}`);
                    providerAccounts[provider] = [];
                }
            }
        }

        function updateAccountSelection() {
            const providerSelect = document.getElementById('dns_provider_select');
            const accountContainer = document.getElementById('account-selection-container');
            const accountSelect = document.getElementById('account_select');
            
            const selectedProvider = providerSelect.value;
            
            if (selectedProvider && providerAccounts[selectedProvider] && providerAccounts[selectedProvider].length > 0) {
                // Show account selection
                accountContainer.style.display = 'block';
                
                // Clear and populate account options
                accountSelect.innerHTML = '<option value="">Use default account</option>';
                
                providerAccounts[selectedProvider].forEach(account => {
                    const option = document.createElement('option');
                    option.value = account.account_id;
                    option.textContent = account.name || account.account_id;
                    accountSelect.appendChild(option);
                });
            } else {
                // Hide account selection
                accountContainer.style.display = 'none';
                accountSelect.innerHTML = '<option value="">Use default account</option>';
            }
        }

        function updateCAProviderInfo() {
            const caSelect = document.getElementById('ca_provider_select');
            const infoDiv = document.getElementById('ca-provider-info');
            const selectedCA = caSelect.value;
            
            if (selectedCA) {
                let infoText = '';
                switch (selectedCA) {
                    case 'letsencrypt':
                        infoText = '<i class="fas fa-leaf mr-1 text-green-500"></i> Free certificates with 90-day validity and automatic renewal';
                        break;
                    case 'digicert':
                        infoText = '<i class="fas fa-shield-alt mr-1 text-blue-500"></i> Enterprise certificates (requires EAB credentials configured in Settings)';
                        break;
                    case 'private_ca':
                        infoText = '<i class="fas fa-building mr-1 text-purple-500"></i> Internal CA certificates (requires ACME URL configured in Settings)';
                        break;
                }
                infoDiv.innerHTML = infoText;
                infoDiv.classList.remove('hidden');
            } else {
                infoDiv.classList.add('hidden');
            }
        }

        function toggleAdvancedOptions() {
            const optionsDiv = document.getElementById('advanced-options');
            const chevron = document.getElementById('advanced-chevron');
            
            if (optionsDiv.classList.contains('hidden')) {
                optionsDiv.classList.remove('hidden');
                chevron.classList.add('rotate-180');
            } else {
                optionsDiv.classList.add('hidden');
                chevron.classList.remove('rotate-180');
            }
        }

        // Create certificate
        document.getElementById('createCertForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const domain = document.getElementById('domain').value;
            const dnsProvider = document.getElementById('dns_provider_select').value;
            const accountId = document.getElementById('account_select').value;
            const caProvider = document.getElementById('ca_provider_select').value;
            
            if (!domain) {
                showMessage('Please enter a domain', 'error');
                return;
            }
            
            const progressInterval = showLoadingModal(
                `Creating Certificate for ${domain}`, 
                'Validating domain ownership and generating certificate...'
            );
            
            const requestBody = { domain };
            if (dnsProvider) {
                requestBody.dns_provider = dnsProvider;
            }
            if (accountId) {
                requestBody.account_id = accountId;
            }
            if (caProvider) {
                requestBody.ca_provider = caProvider;
            }
            
            try {
                const response = await fetch('/api/certificates/create', {
                    method: 'POST',
                    headers: API_HEADERS,
                    body: JSON.stringify(requestBody),
                });
                
                const result = await response.json();
                
                if (result.success) {
                    showMessage(`Certificate created successfully for ${domain}!`);
                    document.getElementById('domain').value = '';
                    document.getElementById('dns_provider_select').value = '';
                    document.getElementById('account_select').value = '';
                    document.getElementById('ca_provider_select').value = '';
                    updateAccountSelection(); // Hide account selector
                    loadCertificates();
                } else {
                    showMessage(result.message || 'Failed to create certificate', 'error');
                }
            } catch (error) {
                console.error('Error creating certificate:', error);
                showMessage('Failed to create certificate. Please try again.', 'error');
            } finally {
                hideLoadingModal(progressInterval);
            }
        });

        // Certificate action functions
        async function downloadCertificate(domain) {
            try {
                const response = await fetch(`/api/certificates/${domain}/download`, {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${API_TOKEN}`
                    }
                });
                
                if (response.ok) {
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `${domain}-certificates.zip`;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                    showMessage(`Certificate downloaded for ${domain}`, 'success');
                } else {
                    const errorData = await response.json();
                    showMessage(errorData.error || 'Failed to download certificate', 'error');
                }
            } catch (error) {
                console.error('Error downloading certificate:', error);
                showMessage('Failed to download certificate', 'error');
            }
        }

        async function renewCertificate(domain) {
            const progressInterval = showLoadingModal(
                `Renewing Certificate for ${domain}`, 
                'This may take a few minutes...'
            );
            
            try {
                const response = await fetch(`/api/certificates/${domain}/renew`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${API_TOKEN}`,
                        'Content-Type': 'application/json'
                    }
                });
                
                const result = await response.json();
                
                if (result.success) {
                    showMessage(`Certificate renewal started for ${domain}!`, 'success');
                    // Reload certificates after a short delay to show updated info
                    setTimeout(() => {
                        loadCertificates();
                    }, 2000);
                } else {
                    showMessage(result.message || 'Failed to renew certificate', 'error');
                }
            } catch (error) {
                console.error('Error renewing certificate:', error);
                showMessage('Failed to renew certificate. Please try again.', 'error');
            } finally {
                hideLoadingModal(progressInterval);
            }
        }

        // Copy curl command modal functions
        function copyCurlCommand(domain) {
            const curlCommand = `curl -H "Authorization: Bearer YOUR_API_TOKEN" \\
     -o ${domain}-tls.zip \\
     ${window.location.origin}/${domain}/tls`;
            
            document.getElementById('curlCommandText').textContent = curlCommand;
            document.getElementById('curlModal').classList.remove('hidden');
        }

        function closeCurlModal() {
            document.getElementById('curlModal').classList.add('hidden');
        }

        function copyFromModal() {
            const commandText = document.getElementById('curlCommandText').textContent;
            
            if (navigator.clipboard) {
                navigator.clipboard.writeText(commandText).then(() => {
                    showMessage('Curl command copied to clipboard!', 'success');
                }).catch(err => {
                    console.error('Failed to copy: ', err);
                    // Fallback for older browsers
                    fallbackCopyTextToClipboard(commandText);
                });
            } else {
                // Fallback for older browsers
                fallbackCopyTextToClipboard(commandText);
            }
        }

        function fallbackCopyTextToClipboard(text) {
            const textArea = document.createElement("textarea");
            textArea.value = text;
            textArea.style.top = "0";
            textArea.style.left = "0";
            textArea.style.position = "fixed";
            
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
            
            try {
                const successful = document.execCommand('copy');
                if (successful) {
                    showMessage('Curl command copied to clipboard!', 'success');
                } else {
                    showMessage('Failed to copy command', 'error');
                }
            } catch (err) {
                showMessage('Failed to copy command', 'error');
            }
            
            document.body.removeChild(textArea);
        }

        // Initialize on page load
        document.addEventListener('DOMContentLoaded', function() {
            loadCertificates();
            loadProviderAccounts(); // Load account information
            
            // Initialize search and filters
            document.getElementById('certificateSearch').addEventListener('input', filterCertificates);
            document.getElementById('statusFilter').addEventListener('change', filterCertificates);
            
            // Close modal on outside click
            document.getElementById('curlModal').addEventListener('click', function(e) {
                if (e.target === this) {
                    this.classList.add('hidden');
                }
            });
            
            // Listen for certificate updates from other pages (e.g., settings page)
            try {
                // Listen for BroadcastChannel messages
                if (typeof BroadcastChannel !== 'undefined') {
                    const channel = new BroadcastChannel('certmate_updates');
                    channel.addEventListener('message', function(event) {
                        if (event.data && event.data.type === 'certificates_restored') {
                            console.log('Received certificate update notification from another page');
                            addDebugLog('Certificates updated from another page - refreshing list...', 'info');
                            
                            // Refresh certificates after a short delay
                            setTimeout(() => {
                                loadCertificates();
                                showMessage('Certificate list refreshed - certificates have been restored!', 'success');
                            }, 1000);
                        }
                    });
                }
                
                // Also listen for localStorage changes as fallback
                window.addEventListener('storage', function(event) {
                    if (event.key === 'certificates_updated') {
                        console.log('Detected certificate update via localStorage');
                        addDebugLog('Certificates updated detected - refreshing list...', 'info');
                        
                        // Refresh certificates after a short delay
                        setTimeout(() => {
                            loadCertificates();
                            showMessage('Certificate list refreshed - certificates have been updated!', 'success');
                        }, 1000);
                        
                        // Clean up the signal
                        localStorage.removeItem('certificates_updated');
                    }
                });
                
            } catch (e) {
                console.log('Cross-page communication setup failed:', e);
            }
        });
    </script>
</body>
</html>
